package com.syni.mdd.sjb.community.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.syni.mdd.sjb.common.component.mybatis.community.entity.WxPermanentCode;
import com.syni.mdd.sjb.common.component.utils.common.utils.AppConfig;
import com.syni.mdd.sjb.common.component.utils.common.utils.StringUtils;
import com.syni.mdd.sjb.common.component.utils.redis.utils.RedisTemplateUtils;
import com.syni.mdd.sjb.community.base.config.QywxProperties;
import com.syni.mdd.sjb.community.base.config.QywxThirdApiProperties;
import com.syni.mdd.sjb.community.base.constants.Constants;
import com.syni.mdd.sjb.community.base.service.CommonUtilsServce;
import com.syni.mdd.sjb.community.base.service.WxPermanentCodeService;
import com.syni.mdd.sjb.community.base.utils.OAUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Log4j2
public class CommonUtilsServceImpl implements CommonUtilsServce {
    @Autowired
    WxPermanentCodeService wxPermanentCodeService;

    @Autowired
    QywxThirdApiProperties qywxThirdApiProperties;

    @Autowired
    QywxProperties qywxProperties;

    @Override
    public void handleNotificationAuthorizatio() {
        if(RedisTemplateUtils.hasKey(Constants.REDIS_KEY_AUTH_CODE)){
            Map<String,Object> notificationHandler =  RedisTemplateUtils.getRedisTemplate().opsForHash().entries(Constants.REDIS_KEY_AUTH_CODE);
            if(notificationHandler.size() > 0){
                List<WxPermanentCode> wxPermanentCodeList = new ArrayList<>();
                notificationHandler.forEach((key,value) -> {
                    JSONObject jsonObject = OAUtils.getPermanentCode(key,value.toString());
                    //JSONObject jsonObject = JSON.parseObject("{\"access_token\":\"8-5Gxcf4zWvsAuqtqoQJ7jFVrohv4G8zAVDwCMqj22G7HiEmoYBiPCRYYGTxe28CxsNW77JV9t_ER5L-8iJEZ-1Euxi7L2tgyC0AfigL73H9dfmYLJt9ASw5NzeyG4YMy61MQ9BwAT4J4EPUQk-Kb1r9XUenFJ-e2aUdyfXXqRyyQ1OAKTyoLl7MxsPyTOytJsJF8UzCt3kMs5pAbpJ3hg\",\"expires_in\":7200,\"permanent_code\":\"cNg4S6qOZY_qZNkWCgtgh2Bv4f33_ofcuA98OA9azc4\",\"auth_corp_info\":{\"corpid\":\"ww5ebbdc7619bd41ed\",\"corp_name\":\"珠海横琴电享科技有限公司\",\"corp_type\":\"verified\",\"corp_round_logo_url\":\"http://p.qpic.cn/pic_wework/1415612393/74723564f7cc73a584ad90fdffe98eb1639e6b1e9557edae/0\",\"corp_square_logo_url\":\"https://p.qlogo.cn/bizmail/8FG8liakUQAouDyEBdBqdL8bX2jrUvecwIfwe30ORWDWicwDxwBXk3eA/0\",\"corp_user_max\":200,\"corp_agent_max\":300,\"corp_wxqrcode\":\"https://wework.qpic.cn/wwpic/827657_DWH_-EA0TaWs-27_1594277356/0\",\"corp_full_name\":\"珠海横琴电享科技有限公司\",\"subject_type\":1,\"verified_end_time\":1625215136,\"corp_scale\":\"51-100人\",\"corp_industry\":\"IT服务\",\"corp_sub_industry\":\"互联网和相关服务\",\"location\":\"广东省珠海市\"},\"auth_info\":{\"agent\":[{\"agentid\":1000015,\"name\":\"电享生活\",\"square_logo_url\":\"https://wework.qpic.cn/bizmail/cu3NibwNa05ut1XsFA9okFD8oPfcCNiaAA39icDibqtyoibSc1UMk7HFqvw/0\",\"privilege\":{\"level\":1,\"allow_party\":[],\"allow_user\":[\"FoXin\",\"LinZhiLang\"],\"allow_tag\":[],\"extra_party\":[],\"extra_user\":[],\"extra_tag\":[]}}]},\"auth_user_info\":{\"userid\":\"LinZhiLang\",\"name\":\"林植烺\",\"avatar\":\"http://wework.qpic.cn/bizmail/qo1fNxLickdHBekrhbia6SBwDlRxScYq23xuFZeuEefZl9VDueV2BR6g/0\"}}");
                    if(jsonObject != null){
                        WxPermanentCode wxPermanentCode = new WxPermanentCode();
                        wxPermanentCode.setSuiteId(key);
                        wxPermanentCode.setPermanentCode(jsonObject.getString("permanent_code"));
                        JSONObject auth_corp_info = jsonObject.getJSONObject("auth_corp_info");
                        String corpid = auth_corp_info.getString("corpid");
                        wxPermanentCode.setCorpid(corpid);
                        wxPermanentCode.setNewTime(LocalDateTime.now());
                        if(auth_corp_info.containsKey("corp_full_name")) {
                            wxPermanentCode.setEnterpriseName(auth_corp_info.getString("corp_full_name"));
                        }
                        if(StringUtils.isBlank(wxPermanentCode.getEnterpriseName())){
                            if(auth_corp_info.containsKey("corp_name")){
                                wxPermanentCode.setEnterpriseName(auth_corp_info.getString("corp_name"));
                            }
                        }
                        wxPermanentCode.setResponseBody(JSON.toJSONString(jsonObject));
                        wxPermanentCodeList.add(wxPermanentCode);
                    }
                });
                if(wxPermanentCodeList.size() > 0){
                    wxPermanentCodeService.addList(wxPermanentCodeList);
                }
            }
        }
    }

    @Override
    public String getInstallUrl () {
        try {
            String SuiteID = AppConfig.getProperty("SuiteID");
            String redirectUrl = qywxProperties.getCallbackDomain() + "/sjbApi/community/base/login/appInstall";
            log.info("getInstallUrl:{}",redirectUrl);
            String installPageUrl = String.format("%s?suite_id=%s&pre_auth_code=%s&redirect_uri=%s&state=STATE",qywxThirdApiProperties.getInstall(),
                    SuiteID,OAUtils.getPreAuthCode(),redirectUrl);
            return installPageUrl;
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        return "";
    }

    @Override
    public String getLoginUrl() {
        try {
            String redirectUrl = qywxProperties.getCallbackDomain() + qywxProperties.getLoginUrl();
            log.info("redirectUrl:{}",redirectUrl);
            String loginUrl = String.format("https://open.work.weixin.qq.com/wwopen/sso/3rd_qrConnect?" +
                    "appid=%s&redirect_uri=%s&state=web_login&usertype=admin",
                    AppConfig.getProperty("CorpID"), URLEncoder.encode(redirectUrl,"utf-8"));
            return loginUrl;
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(),e);
        }
        return "";
    }

    @Override
    public String getRegisterUrl() {
        return qywxProperties.getCallbackDomain() + "/sjbApi/community/base/login/registerQywx";
    }

    @Override
    public String getGuidePageUrl() {
        return qywxProperties.getGuidePageUrl();
    }
}
